#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from subprocess import call
import sys
import os
import errno

zt_source_raw = '/data/www/css-js-image.hunantv.com/zt/proj-raw/'
zt_source_publish = '/data/www/css-js-image.hunantv.com/zt/'
zt_front_hist = '/home/ansible/front_page/zt/version-hist/'
remote_ip = '10.1.172.58'
# romote_ip = '192.168.3.101'

# 创建目录 mkdir -p
def mkdir_p(path):
    try:
        os.makedirs(path)
    except OSError as exc:
        if exc.errno == errno.EEXIST and os.path.isdir(path):
            pass
        else:
            raise


# 写入文件
def jsonFile(fileData, filePath):
    file = open(filePath,"w")
    file.write(fileData)
    file.close()


# 文件发布
def publish(project, version):
    ret = 0
    src = zt_source_publish + project + '/' + version
    # css
    if os.path.isdir(src + '/css/'):
        # 创建远程目录/同步
        cmd_mkdir = "ansible %s -m file -a \"path=/data/www/css.hunantv.com/zt/%s/ state=directory\"" % (remote_ip, project)
        cmd_rsync = "ansible %s -m synchronize -a \"src=%s%s/%s/css/ dest=/data/www/css.hunantv.com/zt/%s/ recursive=yes delete=yes\"" % (remote_ip, zt_source_publish, project, version, project)
        ret += call(cmd_mkdir, shell=True)
        ret += call(cmd_rsync, shell=True)
    # js
    if os.path.isdir(src + '/js/'):
        # 创建远程目录/同步
        cmd_mkdir = "ansible %s -m file -a \"path=/data/www/js.hunantv.com/zt/%s/ state=directory\"" % (remote_ip, project)
        cmd_rsync = "ansible %s -m synchronize -a \"src=%s%s/%s/js/ dest=/data/www/js.hunantv.com/zt/%s/ recursive=yes delete=yes\"" % (remote_ip, zt_source_publish, project, version, project)
        ret += call(cmd_mkdir, shell=True)
        ret += call(cmd_rsync, shell=True)

    # img
    if os.path.isdir(src + '/image/'):
        # 创建远程目录/同步
        cmd_mkdir = "ansible %s -m file -a \"path=/data/www/img.hunantv.com/zt/%s/ state=directory\"" % (remote_ip, project)
        cmd_rsync = "ansible %s -m synchronize -a \"src=%s%s/%s/image/ dest=/data/www/img.hunantv.com/zt/%s/ recursive=yes delete=yes\"" % (remote_ip, zt_source_publish, project, version, project)
        ret += call(cmd_mkdir, shell=True)
        ret += call(cmd_rsync, shell=True)

    # flush
    cmd = "curl 'http://wscp.lxdns.com:8080/wsCP/servlet/contReceiver?username=staic&passwd=78fff9dc51f3c6b5b17fb2329fef44c5&dir=css.hunantv.com;js.hunantv.com;img.hunantv.com'"
    ret += call(cmd, shell=True)

    return ret


# 创建相应目录
dirs = [zt_source_raw, zt_source_publish, zt_front_hist]
for dir in dirs:
    mkdir_p(dir)

"""this motivated rsync tries to synchronize forever"""
# rsync -av rsync://10.1.172.104/sync/ /tmp/sync --exclude '.git' --no-motd
source = "rsync://10.1.172.104/sync/zt/"
rsync = "rsync"
arguments = "-a --exclude '.git' --no-motd --delete"
cmd = "%s %s %s %s" % (rsync, arguments, source, zt_source_raw)
ret = call(cmd, shell=True)
if ret != 0:
    print("rsync zt failed!")
    sys.exit(ret)

zt_version_file = zt_source_raw + 'version.json'
if os.path.isfile(zt_version_file):
    with open(zt_version_file) as data_file:
        data = json.load(data_file)
else:
    print("file '" + zt_version_file + "' is not exist!")
    exit(2)

pub_project = data['project']
pub_version = data['tag']

# pub_project 不能为空
if pub_project is None or pub_project is "":
    print('project name should not be None!')
    exit(3)

# 更新操作
# rsync到对应本目录
src_raw = zt_source_raw + pub_project + "/"
src_published = zt_source_publish + pub_project + "/" + pub_version
#  创建目标目录
mkdir_p(src_published)
rsync = "rsync"
arguments = "-a --exclude '.git' --no-motd --delete"
cmd = "%s %s %s %s" % (rsync, arguments, src_raw, src_published)
ret = call(cmd, shell=True)
if ret != 0:
    print ("rsync zt failed!")
    sys.exit(ret)

#  获取项目发布的历史json信息
version_hist_file = zt_front_hist + pub_project + '.json'
if os.path.isfile(version_hist_file):
    with open(version_hist_file) as json_data:
        version_hist_src = json.load(json_data)

    #  如果版本相同则不发布了，如果不同，则发布
    if pub_version == version_hist_src['release']['tag']:
        print("和线上版本相同，不用发布！")
        exit(1)
    else:
        #  更新项目发布的json信息
        version_hist_src['last'] = version_hist_src['release']
        version_hist_src['release'] = data
        version_hist_src[pub_version] = data
        version_hist = json.dumps(version_hist_src)
else:
    version_hist_src = {"release": data, "last": data, pub_version: data}
    version_hist = json.dumps(version_hist_src)

# 发布代码
ret = publish(pub_project, pub_version)
if ret == 0:
    jsonFile(version_hist, version_hist_file)